package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

type AuthMiddleware struct {
	ignorePaths []string // 要忽略的路径
}

func NewAuthMiddleware() *AuthMiddleware {
	return &AuthMiddleware{}
}

// IgnorePaths 添加忽略路径
func (am *AuthMiddleware) IgnorePaths(paths ...string) *AuthMiddleware {
	am.ignorePaths = append(am.ignorePaths, paths...)
	return am
}

// isIgnored 检查请求路径是否被忽略
func (am *AuthMiddleware) isIgnored(path string) bool {
	for _, ignorePath := range am.ignorePaths {
		if strings.HasPrefix(path, ignorePath) {
			return true
		}
	}
	return false
}

// respondUnauthorized 返回未授权的响应
func (am *AuthMiddleware) respondUnauthorized(ctx *gin.Context, message string) {
	ctx.JSON(http.StatusUnauthorized, gin.H{
		"code":    http.StatusUnauthorized,
		"message": message,
		"data":    nil,
	})
	ctx.Abort()
}

// Build 构建中间件
func (am *AuthMiddleware) Build() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		if am.isIgnored(ctx.Request.URL.Path) {
			ctx.Next() // 忽略路径直接放行
			return
		}

		// 检查 Authorization 头
		tokenHeader := ctx.GetHeader("Authorization")
		if tokenHeader == "" {
			am.respondUnauthorized(ctx, "用户未登录")
			return
		}

		// 验证 Authorization 格式
		segs := strings.Split(tokenHeader, " ")
		if len(segs) != 2 {
			am.respondUnauthorized(ctx, "无效的授权格式")
			return
		}

		// 解析 Token
		tokenStr := segs[1]
		token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
			return []byte("auth_sign"), nil
		})

		if err != nil || token == nil || !token.Valid {
			am.respondUnauthorized(ctx, "无效的 Token")
			return
		}

		// Token 有效，放行请求
		ctx.Next()
	}
}
